from typing import Any, Text, Dict, List
from rasa_sdk import Action, Tracker
from rasa_sdk.executor import CollectingDispatcher
from .neo4j_connection import graph
from .api_instance import api_instance


class ActionAskEventOnPlace(Action):
    def name(self) -> Text:
        return "action_ask_event_on_place"

    async def run(self, dispatcher: CollectingDispatcher,
            tracker: Tracker,
            domain: Dict[Text, Any]) -> List[Dict[Text, Any]]:
        place_name = next(tracker.get_latest_entity_values("place"), None)

        if not place_name:
            api_instance.ask(tracker.events, dispatcher)
            return []

        place_list = graph.query_place(place_name)

        if not place_list:
            dispatcher.utter_message("不好意思，我不清楚你问的" + (place_name if place_name else "") + "是哪里。", attachment="finish")
            return []

        event_list = graph.query_event_on_place(place_name)

        if not event_list:
            dispatcher.utter_message(place_name + "很平静，没有发生过什么有趣的事情。", attachment="finish")

        message = place_name + "发生过这些事：\n"

        for record in event_list:
            message += record["event"] + "\n"

        api_instance.optimize_response(tracker.events, message, dispatcher)
        return []
